import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:fnos_tv_desktop/application/nav.dart';
import 'package:fnos_tv_desktop/core/api/api_auth.dart';

import '../api.dart';
import '../api_exception.dart';

class LoginInterceptor extends Interceptor {
  final Api api;

  LoginInterceptor(this.api);
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    final authorization = api.token;
    if (authorization == null || authorization.isEmpty) {
      if (kDebugMode) {
        print(
          'LoginInterceptor: Authorization is null or empty, redirect to login',
        );
      }
      Nav.logout();
      return;
    }
    options.headers['Authorization'] = authorization;
    options.headers['Authx'] = generateSignature(options);
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    final json = response.data;
    final code = json['code'] as int;
    if (code == -2) {
      if (kDebugMode) {
        print('LoginInterceptor: response code is -2, redirect to login');
      }
      Nav.logout();
    } else if (code == 0) {
      response.data = json['data'];
      super.onResponse(response, handler);
    } else {
      throw ApiException(code, json['msg']);
    }
  }
}
